/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: ShadowDrawable.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.Drawable;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;

import io.bhex.app.R;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.view.BlurBitmap;

public class ShadowDrawable extends Drawable {

    private Paint mPaint1;
    private Paint mPaint;
    private int mShadowRadius;
    private int mShape;
    private int mShapeRadius;
    private int mOffsetX;
    private int mOffsetY;
    private int mBgColor[];
    private RectF mRect;

    public final static int SHAPE_ROUND = 1;
    public final static int SHAPE_CIRCLE = 2;

    private ShadowDrawable(int shape, int[] bgColor, int shapeRadius, int shadowColor, int shadowRadius, int offsetX, int offsetY) {
        this.mShape = shape;
        this.mBgColor = bgColor;
        this.mShapeRadius = shapeRadius;
        this.mShadowRadius = shadowRadius;
        this.mOffsetX = offsetX;
        this.mOffsetY = offsetY;
        mPaint = new Paint();
        mPaint.setColor(Color.TRANSPARENT);
        mPaint.setAntiAlias(true);
        mPaint.setShadowLayer(shadowRadius, offsetX, offsetY, shadowColor);
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP));

//        mPaint1 = new Paint();
//        mPaint1.setColor(Color.TRANSPARENT);
//        mPaint1.setAntiAlias(true);
//        mPaint1.setShadowLayer(shadowRadius*2, 0, 0, shadowColor);
//        mPaint1.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP));
    }

    @Override
    public void setBounds(int left, int top, int right, int bottom) {
        super.setBounds(left, top, right, bottom);
        mRect = new RectF(left + mShadowRadius - mOffsetX, top + mShadowRadius - mOffsetY, right - mShadowRadius - mOffsetX,
                bottom - mShadowRadius - mOffsetY);
    }

    @Override
    public void draw(@NonNull Canvas canvas) {
        Paint newPaint = new Paint();
        if (mBgColor != null) {
            if (mBgColor.length == 1) {
                newPaint.setColor(mBgColor[0]);
            } else {
                newPaint.setShader(new LinearGradient(mRect.left, mRect.height() / 2, mRect.right, mRect.height() / 2, mBgColor,
                        null, Shader.TileMode.CLAMP));
            }
        }
        newPaint.setAntiAlias(true);
        if (mShape == SHAPE_ROUND) {
//            canvas.drawRoundRect(mRect, mShapeRadius, mShapeRadius, mPaint1);
            canvas.drawRoundRect(mRect, mShapeRadius, mShapeRadius, mPaint);
            canvas.drawRoundRect(mRect, mShapeRadius, mShapeRadius, newPaint);
        } else {
            canvas.drawCircle(mRect.centerX(), mRect.centerY(), Math.min(mRect.width(), mRect.height())/ 2, mPaint);
            canvas.drawCircle(mRect.centerX(), mRect.centerY(), Math.min(mRect.width(), mRect.height())/ 2, newPaint);

        }
    }

    @Override
    public void setAlpha(int alpha) {
        mPaint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(@Nullable ColorFilter colorFilter) {
        mPaint.setColorFilter(colorFilter);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    public static void setShadowDrawable(View view, Drawable drawable) {
        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        ViewCompat.setBackground(view, drawable);
    }

    public static void setShadowDrawable(View view, int shapeRadius, int shadowColor, int shadowRadius, int offsetX, int offsetY) {
        ShadowDrawable drawable = new ShadowDrawable.Builder()
                .setShapeRadius(shapeRadius)
                .setShadowColor(shadowColor)
                .setShadowRadius(shadowRadius)
                .setOffsetX(offsetX)
                .setOffsetY(offsetY)
                .builder();
        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        ViewCompat.setBackground(view, drawable);
    }

    public static void setShadowDrawable(View view, int bgColor, int shapeRadius, int shadowColor, int shadowRadius, int offsetX, int offsetY) {
        ShadowDrawable drawable = new ShadowDrawable.Builder()
                .setBgColor(bgColor)
                .setShapeRadius(shapeRadius)
                .setShadowColor(shadowColor)
                .setShadowRadius(shadowRadius)
                .setOffsetX(offsetX)
                .setOffsetY(offsetY)
                .builder();
        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        ViewCompat.setBackground(view, drawable);
    }

    public static void setShadowDrawable(View view, int shape, int bgColor, int shapeRadius, int shadowColor, int shadowRadius, int offsetX, int offsetY) {
        ShadowDrawable drawable = new ShadowDrawable.Builder()
                .setShape(shape)
                .setBgColor(bgColor)
                .setShapeRadius(shapeRadius)
                .setShadowColor(shadowColor)
                .setShadowRadius(shadowRadius)
                .setOffsetX(offsetX)
                .setOffsetY(offsetY)
                .builder();
        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        ViewCompat.setBackground(view, drawable);
    }

    public static void setShadowDrawable(View view, int[] bgColor, int shapeRadius, int shadowColor, int shadowRadius, int offsetX, int offsetY) {
        ShadowDrawable drawable = new ShadowDrawable.Builder()
                .setBgColor(bgColor)
                .setShapeRadius(shapeRadius)
                .setShadowColor(shadowColor)
                .setShadowRadius(shadowRadius)
                .setOffsetX(offsetX)
                .setOffsetY(offsetY)
                .builder();
        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        ViewCompat.setBackground(view, drawable);
    }

    /**
     * 设置背景和阴影
     *
     * @param view
     */
    public static void setShadow(View view) {
        setShadowDrawable(view,
//                getResources().getColor(R.color.white),
                PixelUtils.dp2px(4),
//                view.getContext().getResources().getColor(R.color.dark20),
                SkinColorUtil.getDark20(view.getContext()),
                PixelUtils.dp2px(4),
                PixelUtils.dp2px(1),
                PixelUtils.dp2px(1));
    }

    /**
     * 设置背景和阴影
     *
     * @param view
     */
    public static void setShadow(View view,int shadowColor) {
        setShadowDrawable(view,
//                getResources().getColor(R.color.white),
                PixelUtils.dp2px(2),
                shadowColor,
                PixelUtils.dp2px(2),
                0,
                PixelUtils.dp2px(1));
    }

    /**
     * 设置背景和阴影
     *
     * @param view
     */
    public static void setShadowCircle(View view) {
        setShadowDrawable(view,
                SHAPE_CIRCLE,
                SkinColorUtil.getWhite(view.getContext()),
                PixelUtils.dp2px(2),
                SkinColorUtil.getDark10(view.getContext()),
                PixelUtils.dp2px(2),
                0,
                PixelUtils.dp2px(1));
    }

    /**
     * 设置背景和阴影
     *
     * @param view
     */
    public static void setShadowCircle(View view,int bgColor,int shadowColor) {
        setShadowDrawable(view,
                SHAPE_CIRCLE,
                bgColor,
                PixelUtils.dp2px(2),
                shadowColor,
                PixelUtils.dp2px(2),
                0,
                PixelUtils.dp2px(1));
    }

    public static class Builder {
        private int mShape;
        private int mShapeRadius;
        private int mShadowColor;
        private int mShadowRadius;
        private int mOffsetX = 0;
        private int mOffsetY = 0;
        private int[] mBgColor;

        public Builder() {
            mShape = ShadowDrawable.SHAPE_ROUND;
            mShapeRadius = 12;
            mShadowColor = Color.parseColor("#4d000000");
            mShadowRadius = 18;
            mOffsetX = 0;
            mOffsetY = 0;
            mBgColor = new int[1];
            mBgColor[0] = Color.TRANSPARENT;
        }

        public Builder setShape(int mShape) {
            this.mShape = mShape;
            return this;
        }

        public Builder setShapeRadius(int ShapeRadius) {
            this.mShapeRadius = ShapeRadius;
            return this;
        }

        public Builder setShadowColor(int shadowColor) {
            this.mShadowColor = shadowColor;
            return this;
        }

        public Builder setShadowRadius(int shadowRadius) {
            this.mShadowRadius = shadowRadius;
            return this;
        }

        public Builder setOffsetX(int OffsetX) {
            this.mOffsetX = OffsetX;
            return this;
        }

        public Builder setOffsetY(int OffsetY) {
            this.mOffsetY = OffsetY;
            return this;
        }

        public Builder setBgColor(int BgColor) {
            this.mBgColor[0] = BgColor;
            return this;
        }

        public Builder setBgColor(int[] BgColor) {
            this.mBgColor = BgColor;
            return this;
        }

        public ShadowDrawable builder() {
            return new ShadowDrawable(mShape, mBgColor, mShapeRadius, mShadowColor, mShadowRadius, mOffsetX, mOffsetY);
        }
    }

    /**
     * 获取当前activity模糊背景
     * @param activity
     * @return
     */
    public static Bitmap getBlurBg(Activity activity) {
        Window window = activity.getWindow();
        ViewGroup decorView = window.getDecorView().findViewById(android.R.id.content);
        decorView.setBackgroundColor(SkinColorUtil.getDark80(activity));

        /**支持毛玻璃效果处理**************/
        long startMs = System.currentTimeMillis();
        // 获取截图
        View activityView = window.getDecorView();
        activityView.setDrawingCacheEnabled(true);
        activityView.destroyDrawingCache();
        activityView.buildDrawingCache();
        Bitmap bmp = activityView.getDrawingCache();
        DebugLog.d("MS", "getDrawingCache take away:" + (System.currentTimeMillis() - startMs) + "ms");
        // 模糊处理并保存
        Bitmap blurBg = BlurBitmap.blur(activity, bmp);
        DebugLog.d("MS", "blur take away:" + (System.currentTimeMillis() - startMs) + "ms");
        // 设置成dialog的背景
//        window.setBackgroundDrawable(new BitmapDrawable(context.getResources(), blurBg));
//        decorView.setBackgroundDrawable(new BitmapDrawable(context.getResources(), blurBg));
//        bmp.recycle();

        //设置毛玻璃
//        rootView.setBackgroundDrawable(new BitmapDrawable(context.getResources(), blurBg));
//        bmp.recycle();

        bmp.recycle();
        return blurBg;
    }

    public static void setIconColor(ImageView icon, int r, int g, int b, int a) {
        float[] colorMatrix = new float[]{
                0, 0, 0, 0, r,
                0, 0, 0, 0, g,
                0, 0, 0, 0, b,
                0, 0, 0, (float) a / 255, 0
        };
        icon.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
    }
}
